package cn.edu.buaa.treehole.service;

import cn.edu.buaa.treehole.dao.ContentDao;
import cn.edu.buaa.treehole.pojo.dao.ContentDaoInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ContentService {
    private final ContentDao contentDao;
    private static final int CONTENT_MAX_LENGTH = 128;

    @Autowired
    public ContentService(ContentDao contentDao) {
        this.contentDao = contentDao;
    }

    private String selectAndConnect(long pid, long rid) {
        List<ContentDaoInfo> contents = contentDao.selectAllAscendingContentById(pid, rid);
        StringBuilder sb = new StringBuilder();
        for (ContentDaoInfo content : contents) {
            sb.append(content.getContents());
        }
        return sb.toString();
    }

    private void divideAndInsert(long pid, long rid, String content) {
        int strLength = CONTENT_MAX_LENGTH / 2;
        int end = 0;
        int ord = 0;
        while (end < content.length()) {
            int beg = end;
            end += strLength;
            if (end > content.length())
            {
                end = content.length();
            }
            String sub = content.substring(beg, end);
            ContentDaoInfo contentDaoInfo = new ContentDaoInfo();
            contentDaoInfo.setContents(sub);
            contentDaoInfo.setOrd(ord++);
            contentDaoInfo.setPid(pid);
            contentDaoInfo.setRid(rid);
            contentDao.insertContent(contentDaoInfo);
        }
    }

    public String getPostAbstract(long pid) {
        return contentDao.selectFirstContentById(pid).getContents();
    }

    public String getPostContent(long pid) {
        return selectAndConnect(pid, 0);
    }

    public String getReplyContent(long pid, long rid) {
        assert rid > 0;
        return selectAndConnect(pid, rid);
    }

    public void addReplyContent(long pid, long rid, String content) {
        assert rid > 0;
        divideAndInsert(pid, rid, content);
    }

    public void addPostContent(long pid, String content) {
        divideAndInsert(pid, 0, content);
    }

    public void deleteAllPostContent(long pid) {
        contentDao.deleteAllPostContentByPid(pid);
    }

    public void deleteReplyContent(long pid, long rid) {
        assert rid > 0;
        contentDao.deleteAllReplyContentById(pid, rid);
    }
}
